package cn.yoaket.service;

import cn.yoaket.exception.BoostStrapException;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Alex
 */
public class BootstrapService {

    private BootstrapService(){

    }
    public static String read(String path) throws IOException {

        StringBuilder content = new StringBuilder();
        InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(path);
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        String line;
        while((line = reader.readLine()) != null){
            content.append(line).append("\n");
        }
        content.deleteCharAt(content.length()-1);
        return content.toString();
    }

    private static boolean legal(String str){
        //只可以出现字母数字和点号
        String regx = "^\\w+.+$";
        Pattern pattern = Pattern.compile(regx);
        Matcher matcher = pattern.matcher(str);
        return !matcher.find();
    }

    public static String parse(String content) throws BoostStrapException {
        //这里需要处理的异常有格式不正确异常,找不到属性异常
        var lines = content.split("\n");
        for(var line: lines){
            var map = line.split("=");

            if(map.length != 2 || legal(map[0]) || legal(map[1])){
                throw new BoostStrapException(BoostStrapException.Type.FORMAT_ERROR);
            }

            if("booststrapClass".equals(map[0])){
                return map[1];
            }
        }
        //运行到这里说明没有booststrapClass属性
        throw  new BoostStrapException(BoostStrapException.Type.FIELD_ERROR);
    }
    public static void initial(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, BoostStrapException {
        Class<?> c =  Class.forName(className);
        Constructor<?> con = c.getConstructor();
        Object obj = con.newInstance();
        var methods = c.getMethods();
        for(var method: methods){
            var annotations = method.getAnnotations();
            for(var annotation: annotations){
                String name = annotation.annotationType().getSimpleName();
                if("InitMethod".equals(name)){
                    if(method.getParameterCount() > 0){
                        throw new BoostStrapException(BoostStrapException.Type.PARAM_ERROR);
                    }
                    method.invoke(obj);
                }
            }
        }
    }

}


